package com.irain.pp.tool.redis.template;

import com.irain.pp.tool.api.data.DataObject;
import com.irain.pp.tool.redis.spring.PpRedisTemplate;
import com.irain.pp.tool.GenericsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;

import javax.annotation.PostConstruct;

/**
 * @author WangYanPeng
 * @date 2017/11/21 16:50
 */
public abstract class BaseRedisDAO<DO extends DataObject> {

    private Class<DO> doClass = GenericsUtils.getSuperGenericClass(this.getClass(), BaseRedisDAO.class);

    @Autowired
    protected PpRedisTemplate template;
    protected ValueOperations<String, Object> valueOps;
    protected SetOperations<String, Object> setOps;
    protected ZSetOperations<String, Object> zSetOps;

    private static final String PREFIX = "REDIS:";


    @PostConstruct
    public void init() {
        this.valueOps = template.opsForValue();
        this.setOps = template.opsForSet();
        this.zSetOps = template.opsForZSet();
    }

    protected String genKey(String key, String... properties) {
        StringBuilder sb = new StringBuilder(PREFIX + doClass.getSimpleName() + ":" + key + ":");
        if (properties == null || properties.length == 0) return sb.toString();
        for (String property : properties) {
            sb.append(property).append(':');
        }
        return sb.toString();
    }
}
